package com.lovcreate.shop.service.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Administrator on 2016/9/20.
 * 订单号生成
 */
public class OrderNoUtil {

    private static String fillZero(Integer num) {
        if (num < 10) {
            return "0000000" + num;
        } else if (num < 100) {
            return "000000" + num;
        } else if (num < 1000) {
            return "00000" + num;
        } else if (num < 10000) {
            return "0000" + num;
        } else if (num < 100000) {
            return "000" + num;
        } else if (num < 1000000) {
            return "00" + num;
        } else if (num < 10000000) {
            return "0" + num;
        } else {
            return "" + num;
        }
    }

    public static String getOrderNo(String orderType, String orderNo) {
        if (orderNo == null) {
            orderNo = orderType + new SimpleDateFormat("yyyyMMdd").format(new Date()) + "00000001";
        } else {
            try {
                if (new SimpleDateFormat("yyyyMMdd").parse(orderNo.substring(4, 12)).getTime() + 24 * 60 * 60 * 1000 < new Date().getTime()) {
                    orderNo = orderType + new SimpleDateFormat("yyyyMMdd").format(new Date()) + "00000001";
                } else {
                    orderNo = orderType + new SimpleDateFormat("yyyyMMdd").format(new Date()) + fillZero(Integer.parseInt(orderNo.substring(12, 20)) + 1);
                }
            } catch (ParseException e) {
                orderNo = orderType + new SimpleDateFormat("yyyyMMdd").format(new Date()) + "00000001";
            }
        }
        return orderNo;
    }

}
